﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Linq;
using System.Data.SqlClient;

namespace MODULE_KCS
{
    public partial class frm_kcs : Form
    {
        kcsDataContext context = cls_kcs.getcontext();
        int currenrowindex;
        int status_bill = 1;//1:new-2:old
        public frm_kcs()
        {
            InitializeComponent();
        }

        private void txtsophieu_KeyPress(object sender, KeyPressEventArgs e)
        {
            
        }

        private void getinfobill()
        {
            string sophieu = this.txtsophieu.Text;
            if (sophieu != "")
            {
                IEnumerable<NX_phieunhaphang_h> hs = from c in context.NX_phieunhaphang_hs where c.sophieu.Equals(sophieu) select c;
                if (hs.Count() > 0)
                {
                    NX_phieunhaphang_h h = hs.ElementAt(0);
                   
                    IEnumerable<KT_hoadon_l> hoadonls = from c in context.KT_hoadon_ls where c.sophieunhap.Equals(sophieu) select c;
                    if (hoadonls.Count() > 0)//Phieu da thanh toan
                    {
                        status_bill = 2;
                    }
                    else
                    {
                        status_bill = 1;
                    }
                    
                    //this.dtptungay.Value = DateTime.Parse(h.giovao);
                    //this.dtpdenngay.Value = DateTime.Parse(h.giovao);
                    this.cbloaihang.SelectedValue = h.loaimi;
                    if (h.loaimi == constant.MITUOI)
                    {
                        //this.rdmituoi.Checked = true;
                        //this.rdmikho.Checked = false;
                        this.grdata.Columns["truluong"].HeaderText = "Trữ lượng bột";
                    }
                    if (h.loaimi == constant.MIKHO)
                    {
                        //this.rdmituoi.Checked = false;
                        //this.rdmikho.Checked = true;
                        this.grdata.Columns["truluong"].HeaderText = "Số bao";
                        
                    }


                    this.txtmachuhang.Text = h.machuhang;
                    this.txttenchuhang.Text = h.DM_chuhang.tenchuhang;
                    this.txtdiachi.Text = h.DM_chuhang.diachi;
                    this.txtxecho.Text = h.soxe;
                    this.txttrongluongxoi.Text = h.tongtrongluong.ToString();
                    this.txttrongluongbi.Text = h.trongluongxe.ToString();
                    double trongluongcan = (double)(h.tongtrongluong - h.trongluongxe);
                    this.txttrongluongcan.Text = trongluongcan.ToString();

                    string manvkiemdinh = h.nguoikiemhang;
                    this.txtmanvkiemdinh.Text = manvkiemdinh;
                    if (manvkiemdinh != "" && manvkiemdinh != null)
                    {
                        IEnumerable<DM_nhanvien> nhanviens = from c in context.DM_nhanviens where c.manv.Equals(manvkiemdinh) select c;
                        if (nhanviens.Count() > 0 && nhanviens.ElementAt(0).hoten != "")
                        {
                            this.txttennvkiemdinh.Text = nhanviens.ElementAt(0).hoten;
                        }

                    }
                    //else
                    //{
                    //    this.txtmanvkiemdinh.Text = "Enter để tìm";
                    //    this.txttennvkiemdinh.Text="";
                    //}
                    string manvnhaplieu = h.nguoinhaplieu;
                    this.txtmanvnhaplieu.Text = manvnhaplieu;
                    if (manvnhaplieu != "" && manvnhaplieu != null)
                    {
                        IEnumerable<DM_nhanvien> nhanviens = from c in context.DM_nhanviens where c.manv.Equals(manvnhaplieu) select c;
                        if (nhanviens.Count() > 0 && nhanviens.ElementAt(0).hoten != "")
                        {
                            this.txttennvnhaplieu.Text = nhanviens.ElementAt(0).hoten;
                            
                        }
                    }
                    grdata.Rows.Clear();
                    IEnumerable<NX_phieunhaphang_l> ls = from c in context.NX_phieunhaphang_ls where c.sophieu.Equals(h.sophieu) select c;
                    double tongtien = 0;
                    double thanhtien = 0;
                    if (ls.Count() > 0)//phieu da kiem dinh
                    {

                        NX_phieunhaphang_l l;
                        for (int i = 0; i < ls.Count(); i++)
                        {
                            l = ls.ElementAt(i);
                            this.grdata.Rows.Add();
                            this.grdata.Rows[i].Cells["mahh"].Value = l.mahanghoa;
                            this.grdata.Rows[i].Cells["tenhh"].Value = l.DM_hanghoa.tenhang;
                            this.grdata.Rows[i].Cells["danhgia"].Value = l.trongluongdanhgia;
                            if (h.loaimi ==constant.MITUOI)
                            {
                                this.grdata.Rows[i].Cells["truluong"].Value = l.truluong;
                            }
                            if (h.loaimi == constant.MIKHO)
                            {
                                this.grdata.Rows[i].Cells["truluong"].Value = l.sobao;

                            }
                            this.grdata.Rows[i].Cells["thuyphan"].Value = l.thuyphan;
                            this.grdata.Rows[i].Cells["tapchat"].Value = l.tapchat;
                            this.grdata.Rows[i].Cells["moc"].Value = l.moc;
                           
                            this.grdata.Rows[i].Cells["bitru"].Value = l.bitru;
                           
                            this.grdata.Rows[i].Cells["thanhtoan"].Value = l.trongluongthanhtoan;

                            double dongia, trongluongdanhgia, thuyphan, tapchat, moc;
                            if (l.dongia != null)
                            {
                                dongia = (double)l.dongia;
                            }
                            else
                            {
                                dongia = 0;
                            }
                            if (l.trongluongdanhgia != null)
                            {
                                trongluongdanhgia = (double)l.trongluongdanhgia;
                            }
                            else
                            {
                                trongluongdanhgia = 0;
                            }
                            if (l.thuyphan != null)
                            {
                                thuyphan = (double)l.thuyphan;
                            }
                            else
                            {
                                thuyphan = 0;
                            }
                            if (l.tapchat != null)
                            {
                                tapchat = (double)l.tapchat;
                            }
                            else
                            {
                                tapchat = 0;
                            }
                            if (l.moc != null)
                            {
                                moc = (double)l.moc;
                            }
                            else
                            {
                                moc = 0;
                            }



                            this.grdata.Rows[i].Cells["dongia"].Value = l.dongia;
                            IEnumerable<dongiahanghoamoinhat> dongiamoinhat = from c in context.dongiahanghoamoinhats where c.mahang.Equals(l.mahanghoa) select c;
                            double dongiahienhanh = 0;
                            if (dongiamoinhat.Count() > 0)
                            {
                                dongiahienhanh = (double)dongiamoinhat.ElementAt(0).dongia;
                            }

                            this.grdata.Rows[i].Cells["dongiahienhanh"].Value = dongiahienhanh; 



                            thanhtien = dongia * (double)l.trongluongthanhtoan;
                            this.grdata.Rows[i].Cells["thanhtien"].Value = thanhtien;
                            tongtien += thanhtien;

                        }

                    }
                    else//phieu chua kiem dinh
                    {
                        this.grdata.Rows.Clear();
                        this.grdata.Rows.Add();
                        this.grdata.Rows[0].Cells["danhgia"].Value = (double)(h.tongtrongluong - h.trongluongxe);
                        this.grdata.Rows[0].Cells["thanhtoan"].Value = (double)(h.tongtrongluong - h.trongluongxe);
                        if (h.loaimi == "2")
                        {
                            double trongluongdanhgia;
                            double sobao;
                            IEnumerable<thamso> t = from c in context.thamsos where c.tenthamso.Equals("trongluongtrenbao") select c;
                            int trongluongtrenbao = int.Parse(t.ElementAt(0).giatri.ToString());

                            if (this.grdata.CurrentRow.Cells["danhgia"].Value != null)
                            {
                                trongluongdanhgia = double.Parse(this.grdata.CurrentRow.Cells["danhgia"].Value.ToString());
                            }
                            else
                            {
                                trongluongdanhgia = 0;

                            }
                            sobao = Math.Round(trongluongdanhgia / trongluongtrenbao,0);
                            this.grdata.CurrentRow.Cells["truluong"].Value = sobao;
                        }
                        this.txtmanvkiemdinh.Text = "Enter để tìm";
                        this.txttennvkiemdinh.Text = "";
                        this.txtmanvnhaplieu.Text = "Enter để tìm";
                        this.txttennvnhaplieu.Text = "";
                    }
                    this.txttongtien.Text = tongtien.ToString();
                    

                  

                }
                else//khong co phieu kcs nay
                {

                    this.grdata.Rows.Clear();

                }
                if (status_bill == 1)
                {
                    
                    this.btDelete.Enabled = true;
                    this.btSave.Enabled = true;
                    this.grdata.Enabled = true;
                }
                if (status_bill == 2)
                {
                    this.btSave.Enabled = false;
                    this.btDelete.Enabled = false;
                    
                    this.grdata.Enabled = false;
                }


            }
 
        }
        private void txtsophieu_KeyDown(object sender, KeyEventArgs e)
        {
            
            try
            {
                

                if (e.KeyCode == Keys.Enter)
                {
                    //MessageBox.Show("aa");
                    getinfobill();
                    
                    

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            //MessageBox.Show("tao ne may");
        }

        private void btAdd_Click(object sender, EventArgs e)
        {
            
        }

        private void grdata_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
           
        }

        private void grdata_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
           
      
          
        }

        private void grdata_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            
        }

        private void rdmikho_Click(object sender, EventArgs e)
        {
            this.grdata.Columns["truluong"].HeaderText = "Số bao";
            this.grdata.Columns["truluong"].ReadOnly = true;
        }

        private void grdata_Validated(object sender, EventArgs e)
        {
           
        }

        private void grdata_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //rang buoc nhap lieu kieu so
           //try
           //{
            string sophieu = this.txtsophieu.Text;
            IEnumerable<NX_phieunhaphang_h> phieunhaphs = from c in context.NX_phieunhaphang_hs where c.sophieu.Equals(sophieu) select c;
            if (phieunhaphs.Count() > 0)
            {
                NX_phieunhaphang_h phieunhaph = phieunhaphs.ElementAt(0);
                if (e.ColumnIndex == 2 || e.ColumnIndex == 3 || e.ColumnIndex == 4 || e.ColumnIndex == 5
                    || e.ColumnIndex == 6 || e.ColumnIndex == 7 || e.ColumnIndex == 8 || e.ColumnIndex == 9 || e.ColumnIndex == 10)
                {
                    bool flag = true;
                    if (this.grdata.CurrentCell.Value != null)
                    {

                        try
                        {
                            float.Parse(this.grdata.CurrentCell.Value.ToString());
                        }
                        catch
                        {
                            flag = false;
                        }
                    }
                    if (flag == false)
                    {
                        this.grdata.CurrentCell.Value = 0;
                    }
                }

                //Kiem tra va hien thi danh muc hang hoa cho nguoi dung chon


                if (this.tabControl1.SelectedIndex == 0)
                {
                    if (this.grdata.CurrentCell.ColumnIndex == 0)
                    {

                        string mahh;
                        if (this.grdata.CurrentCell.Value != null)
                        {
                            mahh = this.grdata.CurrentCell.Value.ToString();


                            IEnumerable<DM_hanghoa> hanghoas = from c in context.DM_hanghoas where c.mahang.Equals(mahh) select c;
                            
                            if (hanghoas.Count() > 0)
                            {
                                DM_hanghoa h = hanghoas.ElementAt(0);
                                this.grdata.CurrentRow.Cells["tenhh"].Value = h.tenhang;
                                IEnumerable<dongiahanghoamoinhat> dongias = from c in context.dongiahanghoamoinhats where c.mahang.Equals(mahh) select c;
                                if (dongias.Count() > 0)
                                {
                                    dongiahanghoamoinhat dg = dongias.ElementAt(0);
                                    this.grdata.CurrentRow.Cells["dongia"].Value = dg.dongia;
                                    this.grdata.CurrentRow.Cells["dongiahienhanh"].Value = dg.dongia;
                                    double soluong = double.Parse(this.grdata.CurrentRow.Cells["danhgia"].Value.ToString());
                                    double thanhtien = (double)dg.dongia * soluong;
                                    this.grdata.CurrentRow.Cells["thanhtien"].Value = thanhtien;
                                }


                            }
                            else
                            {
                                MODULE_TIENICH.cls_tienich cls = new MODULE_TIENICH.cls_tienich();
                                cls.ShowForm("frm_timkiemhanghoa");
                                this.grdata.CurrentCell.Value = cls._mahanghoa;
                                mahh = this.grdata.CurrentCell.Value.ToString();
                                hanghoas = from c in context.DM_hanghoas where c.mahang.Equals(mahh) select c;
                                DM_hanghoa h = hanghoas.ElementAt(0);
                                this.grdata.CurrentRow.Cells["tenhh"].Value = h.tenhang;
                                IEnumerable<dongiahanghoamoinhat> dongias = from c in context.dongiahanghoamoinhats where c.mahang.Equals(mahh) select c;
                                if (dongias.Count() > 0)
                                {
                                    dongiahanghoamoinhat dg = dongias.ElementAt(0);
                                    this.grdata.CurrentRow.Cells["dongia"].Value = dg.dongia;
                                    this.grdata.CurrentRow.Cells["dongiahienhanh"].Value = dg.dongia;
                                    double soluong = double.Parse(this.grdata.CurrentRow.Cells["danhgia"].Value.ToString());
                                    double thanhtien = (double)dg.dongia * soluong;
                                    this.grdata.CurrentRow.Cells["thanhtien"].Value = thanhtien;
                                }


                            }
                        }
                        else
                        {

                            MODULE_TIENICH.cls_tienich cls = new MODULE_TIENICH.cls_tienich();
                            cls.ShowForm("frm_timkiemhanghoa");
                            this.grdata.CurrentCell.Value = cls._mahanghoa;
                            mahh = this.grdata.CurrentCell.Value.ToString();
                            IEnumerable<DM_hanghoa> hanghoas = from c in context.DM_hanghoas where c.mahang.Equals(mahh) select c;
                            DM_hanghoa h = hanghoas.ElementAt(0);
                            this.grdata.CurrentRow.Cells["tenhh"].Value = h.tenhang;
                            IEnumerable<dongiahanghoamoinhat> dongias = from c in context.dongiahanghoamoinhats where c.mahang.Equals(mahh) select c;
                            if (dongias.Count() > 0)
                            {
                                dongiahanghoamoinhat dg = dongias.ElementAt(0);
                                this.grdata.CurrentRow.Cells["dongia"].Value = dg.dongia;
                                this.grdata.CurrentRow.Cells["dongiahienhanh"].Value = dg.dongia;
                                double soluong = double.Parse(this.grdata.CurrentRow.Cells["danhgia"].Value.ToString());
                                double dongia = 0;
                                if (dg.dongia != null)
                                {
                                    dongia = (double)dg.dongia;
                                }
                                double thanhtien = dongia * soluong;
                                this.grdata.CurrentRow.Cells["thanhtien"].Value = thanhtien;
                            }


                        }
                        ////////////Tinh lai tong tien
                        //double tongtien = 0;
                        //for (int i = 0; i < this.grdata.Rows.Count; i++)
                        //{
                        //    if (grdata.Rows[i].Cells["thanhtien"].Value != null && grdata.Rows[i].Cells["thanhtien"].Value.ToString() != "")
                        //    {
                        //        tongtien += double.Parse(grdata.Rows[i].Cells["thanhtien"].Value.ToString());
                        //    }
                        //}
                        //this.txttongtien.Text = tongtien.ToString();

                    }
                }
                ////tinh toan gia tri.


                if (phieunhaph.loaimi == constant.MIKHO)
                {
                    this.grdata.Columns[3].ReadOnly = true;
                    if (e.ColumnIndex == 2)
                    {
                        double trongluongdanhgia;
                        int  sobao;
                        double  trongluongbitru;
                        double trongluongthanhtoan;
                        double thanhtien;
                        double dg;
                        double thuyphan, tapchat, moc;


                        IEnumerable<thamso> t = from c in context.thamsos where c.tenthamso.Equals("trongluongtrenbao") select c;
                        int trongluongtrenbao = int.Parse(t.ElementAt(0).giatri.ToString());

                        if (this.grdata.CurrentRow.Cells["danhgia"].Value != null)
                        {
                            trongluongdanhgia = double.Parse(this.grdata.CurrentRow.Cells["danhgia"].Value.ToString());
                        }
                        else
                        {
                            trongluongdanhgia = 0;

                        }
                        sobao = (int)trongluongdanhgia / trongluongtrenbao;
                        this.grdata.CurrentRow.Cells["truluong"].Value = sobao;
                        
                        thuyphan = 0;
                        tapchat = 0;
                        moc = 0;

                        if (this.grdata.CurrentRow.Cells["thuyphan"].Value != null)
                        {
                            thuyphan = double.Parse(this.grdata.CurrentRow.Cells["thuyphan"].Value.ToString());
                        }
                        if (this.grdata.CurrentRow.Cells["tapchat"].Value != null)
                        {
                            tapchat = double.Parse(this.grdata.CurrentRow.Cells["tapchat"].Value.ToString());
                        }
                        if (this.grdata.CurrentRow.Cells["moc"].Value != null)
                        {
                            moc = double.Parse(this.grdata.CurrentRow.Cells["moc"].Value.ToString());
                        }
                        trongluongbitru = Math.Round((sobao * 0.2 + trongluongdanhgia * (thuyphan + tapchat + moc)/100),0);
                        this.grdata.CurrentRow.Cells["bitru"].Value = trongluongbitru;

                        trongluongthanhtoan = 0;
                        if (trongluongdanhgia > trongluongbitru)
                        {
                            trongluongthanhtoan = Math.Round((trongluongdanhgia - trongluongbitru),0);

                        }
                        dg = 0;
                        if (this.grdata.CurrentRow.Cells["dongia"].Value != null)
                        {
                            dg = double.Parse(this.grdata.CurrentRow.Cells["dongia"].Value.ToString());
                        }
                        this.grdata.CurrentRow.Cells["thanhtoan"].Value = trongluongthanhtoan;
                        thanhtien = trongluongthanhtoan * dg;
                        this.grdata.CurrentRow.Cells["thanhtien"].Value = thanhtien;

                    }
                    if (e.ColumnIndex == 4 || e.ColumnIndex == 5 || e.ColumnIndex == 6)
                    {
                        double trongluongdanhgia;
                        //float sobao;
                        double trongluongbitru;
                        double trongluongthanhtoan;
                        double thanhtien;
                        double dg;
                        double thuyphan, tapchat, moc;
                        trongluongdanhgia = 0;
                        if (this.grdata.CurrentRow.Cells["danhgia"].Value != null)
                        {
                            trongluongdanhgia = double.Parse(this.grdata.CurrentRow.Cells["danhgia"].Value.ToString());
                        }

                        thuyphan = 0;
                        tapchat = 0;
                        moc = 0;
                        if (this.grdata.CurrentRow.Cells["thuyphan"].Value != null)
                        {
                            thuyphan = double.Parse(this.grdata.CurrentRow.Cells["thuyphan"].Value.ToString());
                        }
                        if (this.grdata.CurrentRow.Cells["tapchat"].Value != null)
                        {
                            tapchat = double.Parse(this.grdata.CurrentRow.Cells["tapchat"].Value.ToString());
                        }
                        if (this.grdata.CurrentRow.Cells["moc"].Value != null)
                        {
                            moc = double.Parse(this.grdata.CurrentRow.Cells["moc"].Value.ToString());
                        }
                        IEnumerable<thamso> t = from c in context.thamsos where c.tenthamso.Equals("trongluongtrenbao") select c;
                        int trongluongtrenbao = int.Parse(t.ElementAt(0).giatri.ToString());

                        int sobao;
                        sobao = (int)trongluongdanhgia / trongluongtrenbao;
                        trongluongbitru = Math.Round(sobao * 0.2 + trongluongdanhgia * (thuyphan + tapchat + moc)/100);
                        this.grdata.CurrentRow.Cells["bitru"].Value = trongluongbitru;
                        trongluongthanhtoan = 0;
                        if (trongluongdanhgia > trongluongbitru)
                        {
                            trongluongthanhtoan = Math.Round((trongluongdanhgia - trongluongbitru),0);

                        }
                        dg = 0;
                        if (this.grdata.CurrentRow.Cells["dongia"].Value != null)
                        {
                            dg = double.Parse(this.grdata.CurrentRow.Cells["dongia"].Value.ToString());
                        }
                        this.grdata.CurrentRow.Cells["thanhtoan"].Value = trongluongthanhtoan;
                        thanhtien = trongluongthanhtoan * dg;
                        this.grdata.CurrentRow.Cells["thanhtien"].Value = thanhtien;



                    }

                }
                else
                {
                    this.grdata.Columns[3].ReadOnly = false;
                    if (phieunhaph.loaimi == constant.MITUOI)//Mi tuoi
                    {
                        if (e.ColumnIndex == 2 || e.ColumnIndex == 3 || e.ColumnIndex == 4 || e.ColumnIndex == 5 || e.ColumnIndex == 6)
                        {
                            double truluongbot = 0, truluongbotcaonhat, truluongbottrungbinh, truluongbotthapnhat;

                            if (this.grdata.CurrentRow.Cells["truluong"].Value != null)
                            {
                                truluongbot = double.Parse(this.grdata.CurrentRow.Cells["truluong"].Value.ToString());
                            }


                            IEnumerable<thamso> t = from c in context.thamsos where c.tenthamso.Equals("truluongbotthapnhat") select c;
                            truluongbotthapnhat = double.Parse(t.ElementAt(0).giatri.ToString());
                            t = from c in context.thamsos where c.tenthamso.Equals("truluongbottrungbinh") select c;
                            truluongbottrungbinh = double.Parse(t.ElementAt(0).giatri.ToString());
                            t = from c in context.thamsos where c.tenthamso.Equals("truluongbotcaonhat") select c;
                            truluongbotcaonhat = double.Parse(t.ElementAt(0).giatri.ToString());
                            double dongiahienhanh = 0;
                            double dongiathucte;
                            if (this.grdata.CurrentRow.Cells["dongiahienhanh"].Value != null)
                            {
                                dongiahienhanh = double.Parse(this.grdata.CurrentRow.Cells["dongiahienhanh"].Value.ToString());
                            }
                            dongiathucte = dongiahienhanh;
                            if (truluongbot >= truluongbottrungbinh && truluongbot < truluongbotcaonhat)
                            {
                                dongiathucte = dongiahienhanh - (truluongbotcaonhat - truluongbot) * 20;

                            }
                            if (truluongbot >= truluongbotthapnhat && truluongbot < truluongbottrungbinh)
                            {
                                dongiathucte = dongiahienhanh - (truluongbotcaonhat - truluongbot) * 30;
                            }
                            if (truluongbot < truluongbotthapnhat)
                            {
                                dongiathucte = dongiahienhanh - (truluongbotcaonhat - truluongbot) * 80;
                            }
                            this.grdata.CurrentRow.Cells["dongia"].Value = dongiathucte;
                            double thuyphan = 0;
                            double tapchat = 0;
                            double moc = 0;
                            if (this.grdata.CurrentRow.Cells["thuyphan"].Value != null)
                            {
                                thuyphan = double.Parse(this.grdata.CurrentRow.Cells["thuyphan"].Value.ToString());
                            }
                            if (this.grdata.CurrentRow.Cells["tapchat"].Value != null)
                            {
                                tapchat = double.Parse(this.grdata.CurrentRow.Cells["tapchat"].Value.ToString());
                            }
                            if (this.grdata.CurrentRow.Cells["moc"].Value != null)
                            {
                                moc = double.Parse(this.grdata.CurrentRow.Cells["moc"].Value.ToString());
                            }
                            double trongluongdanhgia;
                            if (this.grdata.CurrentRow.Cells["danhgia"].Value != null)
                            {
                                trongluongdanhgia = double.Parse(this.grdata.CurrentRow.Cells["danhgia"].Value.ToString());
                            }
                            else
                            {
                                trongluongdanhgia = 0;
                            }
                            double trongluongbitru = trongluongdanhgia*(thuyphan + tapchat + moc)/100;
                            this.grdata.CurrentRow.Cells["bitru"].Value = trongluongbitru;

                            
                           
                            double trongluongthanhtoan = 0;
                            if (trongluongdanhgia > trongluongbitru)
                            {
                                trongluongthanhtoan = Math.Round((trongluongdanhgia - trongluongbitru),0);

                            }
                            this.grdata.CurrentRow.Cells["thanhtoan"].Value = trongluongthanhtoan;
                            double fthanhtien = dongiathucte * trongluongthanhtoan;
                            this.grdata.CurrentRow.Cells["thanhtien"].Value = fthanhtien;



                        }

                    }
                    else
                    {
                        //Cac mat hang khac
                        if (e.ColumnIndex == 2 || e.ColumnIndex == 3 || e.ColumnIndex == 4 || e.ColumnIndex == 5 || e.ColumnIndex == 6)
                        {
                            double thuyphan = 0;
                            double tapchat = 0;
                            double moc = 0;
                            if (this.grdata.CurrentRow.Cells["thuyphan"].Value != null)
                            {
                                thuyphan = double.Parse(this.grdata.CurrentRow.Cells["thuyphan"].Value.ToString());
                            }
                            if (this.grdata.CurrentRow.Cells["tapchat"].Value != null)
                            {
                                tapchat = double.Parse(this.grdata.CurrentRow.Cells["tapchat"].Value.ToString());
                            }
                            if (this.grdata.CurrentRow.Cells["moc"].Value != null)
                            {
                                moc = double.Parse(this.grdata.CurrentRow.Cells["moc"].Value.ToString());
                            }
                            double trongluongdanhgia;
                            if (this.grdata.CurrentRow.Cells["danhgia"].Value != null)
                            {
                                trongluongdanhgia = double.Parse(this.grdata.CurrentRow.Cells["danhgia"].Value.ToString());
                            }
                            else
                            {
                                trongluongdanhgia = 0;
                            }
                            double trongluongbitru = trongluongdanhgia*(thuyphan + tapchat + moc)/100;
                            this.grdata.CurrentRow.Cells["bitru"].Value = trongluongbitru;

                           
                            double trongluongthanhtoan = 0;
                            if (trongluongdanhgia > trongluongbitru)
                            {
                                trongluongthanhtoan = Math.Round((trongluongdanhgia - trongluongbitru),0);

                            }
                            this.grdata.CurrentRow.Cells["thanhtoan"].Value = trongluongthanhtoan;
                        }


                    }
                }
               
                //Tinh tong tien
                double tongtien = 0;


                for (int i = 0; i < this.grdata.Rows.Count; i++)
                {
                    if (grdata.Rows[i].Cells["thanhtien"].Value != null)
                    {
                        tongtien += double.Parse(grdata.Rows[i].Cells["thanhtien"].Value.ToString());
                    }
                }
                this.txttongtien.Text = tongtien.ToString();
                //}
                //catch (Exception ex)
                //{
                //    MessageBox.Show(ex.Message);
                //}

            }

            
        }

        
        private void grdata_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            

        }

       private void loaddanhsachphieunhaptheongay()
        {
           
            string tungay, denngay;
            string d, m, y;

            if (this.dtptungay.Value.Day >= 10)
            {
                d = this.dtptungay.Value.Day.ToString();
            }
            else
            {
                d = "0" + this.dtptungay.Value.Day.ToString();
            }

            if (this.dtptungay.Value.Month >= 10)
            {
                m = this.dtptungay.Value.Month.ToString();
            }
            else
            {
                m = "0" + this.dtptungay.Value.Month.ToString();
            }
            y = this.dtptungay.Value.Year.ToString();
            tungay = d + "/" + m + "/" + y;
            if (this.dtpdenngay.Value.Day >= 10)
            {
                d = this.dtpdenngay.Value.Day.ToString();
            }
            else
            {
                d = "0" + this.dtpdenngay.Value.Day.ToString();
            }

            if (this.dtpdenngay.Value.Month >= 10)
            {
                m = this.dtpdenngay.Value.Month.ToString();
            }
            else
            {
                m = "0" + this.dtpdenngay.Value.Month.ToString();
            }
            y = this.dtpdenngay.Value.Year.ToString();
            denngay = d + "/" + m + "/" + y;

            //this.grdata.Columns["truluong"].HeaderText = "Trữ lượng bột";
            List<KCS_getdanhsachphieunhaptheongayResult> danhsachphieunhaps = context.KCS_getdanhsachphieunhaptheongay(tungay, denngay).ToList();

            grdanhsach.Rows.Clear();
            for (int i = 0; i < danhsachphieunhaps.Count(); i++)
            {
                KCS_getdanhsachphieunhaptheongayResult phieunhap = danhsachphieunhaps.ElementAt(i);
                grdanhsach.Rows.Add();
                grdanhsach.Rows[i].Cells["sophieu"].Value = phieunhap.sophieu;
                grdanhsach.Rows[i].Cells["ngay"].Value = phieunhap.giovao;
                grdanhsach.Rows[i].Cells["machuhang"].Value = phieunhap.machuhang;
                grdanhsach.Rows[i].Cells["tenchuhang"].Value = phieunhap.tenchuhang;
                grdanhsach.Rows[i].Cells["diachi"].Value = phieunhap.diachi;
                grdanhsach.Rows[i].Cells["soxe"].Value = phieunhap.soxe;
                grdanhsach.Rows[i].Cells["trongluongthuan"].Value = phieunhap.trongluongthanhtoan;
                grdanhsach.Rows[i].Cells["sotien"].Value = phieunhap.tongsotienbangso;

                grdanhsach.Rows[i].DefaultCellStyle.ForeColor = Color.Red;//Mau phieu moi nhap
                IEnumerable<NX_phieunhaphang_l> kiemdinhs = from c in context.NX_phieunhaphang_ls where c.sophieu.Equals(phieunhap.sophieu) select c;
                if (kiemdinhs.Count() > 0)
                {
                    //grdata.Rows[i].Cells["chk"].ReadOnly = true;

                    grdanhsach.Rows[i].DefaultCellStyle.ForeColor = Color.MediumBlue;//System.Drawing.Color.Red;
                }
                IEnumerable<KT_hoadon_l> hoadons = from c in context.KT_hoadon_ls where c.sophieunhap.Equals(phieunhap.sophieu) select c;
                if (hoadons.Count() > 0)
                {
                    //grdata.Rows[i].Cells["chk"].ReadOnly = true;
                    grdanhsach.Rows[i].DefaultCellStyle.ForeColor = Color.Black;//System.Drawing.Color.Red;

                    //flag = false;
                }
            }
        }
    
        private void frm_kcs_Load(object sender, EventArgs e)
        {
            IEnumerable<DM_loaimi> loaimis=from c in context.DM_loaimis select c;
            this.cbloaihang.DataSource = loaimis;
            this.cbloaihang.DisplayMember = "tenloai";
            this.cbloaihang.ValueMember = "maloai";



            try
            {
           
                currenrowindex = 0;
                //this.rdmituoi.Checked = true;
                //this.rdmikho.Checked = false;
                //
                IEnumerable<p_getdateResult> dates = context.p_getdate().AsEnumerable();
                DateTime today = dates.ElementAt(0).serverdatetime;
                this.dtptungay.Value = today;
                this.dtpdenngay.Value = today;
                //this.loaddata();
                loaddanhsachphieunhaptheongay();
                
                //Lay thong tin phieu nhap moi nhat
                List<KCS_getphieunhapmoinhatResult> phieumois = context.KCS_getphieunhapmoinhat().ToList();
                string  phieumoi = phieumois.ElementAt(0).sophieu;
                this.txtsophieu.Text = phieumoi;
                getinfobill();
                //loadthongtinphieunhap(phieumoi);
                ////
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }
        public void loaddata()
        {

            IEnumerable<NX_phieunhaphang_h> list = context.NX_phieunhaphang_hs.AsEnumerable();
            grdanhsach.Rows.Clear();
            for (int i = 0; i < list.Count(); i++)
            {
                NX_phieunhaphang_h phieunhap = list.ElementAt(i);
                grdanhsach.Rows.Add();
                grdanhsach.Rows[i].Cells["sophieu"].Value = phieunhap.sophieu;
                grdanhsach.Rows[i].Cells["ngay"].Value = phieunhap.giovao;
                grdanhsach.Rows[i].Cells["machuhang"].Value = phieunhap.machuhang;
                grdanhsach.Rows[i].Cells["tenchuhang"].Value = phieunhap.DM_chuhang.tenchuhang;
                grdanhsach.Rows[i].Cells["diachi"].Value = phieunhap.DM_chuhang.diachi;
                grdanhsach.Rows[i].Cells["soxe"].Value = phieunhap.soxe;
                grdanhsach.Rows[i].Cells["trongluongthuan"].Value = phieunhap.trongluongthanhtoan;
                grdanhsach.Rows[i].Cells["sotien"].Value = phieunhap.tongsotienbangso;


                grdanhsach.Rows[i].DefaultCellStyle.ForeColor = Color.Red;//Mau phieu moi nhap
                IEnumerable<NX_phieunhaphang_l> kiemdinhs = from c in context.NX_phieunhaphang_ls where c.sophieu.Equals(phieunhap.sophieu) select c;
                if (kiemdinhs.Count() > 0)
                {
                    //grdata.Rows[i].Cells["chk"].ReadOnly = true;

                    grdanhsach.Rows[i].DefaultCellStyle.ForeColor = Color.MediumBlue;//System.Drawing.Color.Red;
                }
                IEnumerable<KT_hoadon_l> hoadons = from c in context.KT_hoadon_ls where c.sophieunhap.Equals(phieunhap.sophieu) select c;
                if (hoadons.Count() > 0)
                {
                    //grdata.Rows[i].Cells["chk"].ReadOnly = true;
                    grdanhsach.Rows[i].DefaultCellStyle.ForeColor = Color.Black;//System.Drawing.Color.Red;

                    //flag = false;
                }

            }
           
                   

        }
        private bool funcvalidate()
        {
            bool kq = true;
            string MaNVKiemDinh = txtmanvkiemdinh.Text;
            string MaNVNhapLieu = txtmanvnhaplieu.Text;
            IEnumerable<DM_nhanvien> nhanvienkiemdinhs = from c in context.DM_nhanviens where c.manv.Equals(MaNVKiemDinh) select c;
            IEnumerable<DM_nhanvien> nhanviennhaplieus = from c in context.DM_nhanviens where c.manv.Equals(MaNVNhapLieu) select c;
 
            
            if (nhanvienkiemdinhs.Count()< 1)
            {
                MessageBox.Show("Chưa có nhân viên kiểm định");
                kq = false;
            }
            if (nhanviennhaplieus.Count() <1)
            {
                kq = false;
                MessageBox.Show("Chưa có nhân viên nhập liệu");
            }

            return kq;
        }

        private void btSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (funcvalidate() == true)
                {
                    
                    MODULE_TIENICH.cls_chuyensothanhchu clsnumbertostring = new MODULE_TIENICH.cls_chuyensothanhchu();
                    
                    string sophieu = this.txtsophieu.Text;
                    IEnumerable<NX_phieunhaphang_h> nhaphangs = from c in context.NX_phieunhaphang_hs where c.sophieu.Equals(sophieu) select c;
                    
                   
                    NX_phieunhaphang_l l;
                    IEnumerable<NX_phieunhaphang_h> hs = from c in context.NX_phieunhaphang_hs where c.sophieu.Equals(sophieu) select c;
                    foreach (NX_phieunhaphang_h phieunhaphang_h in hs)
                    {
                        phieunhaphang_h.nguoinhaplieu = txtmanvnhaplieu.Text;
                        phieunhaphang_h.nguoikiemhang = txtmanvkiemdinh.Text;
                        phieunhaphang_h.tongsotienbangso = double.Parse(this.txttongtien.Text);
                        string  a = clsnumbertostring.DocSoThanhChu(long.Parse(phieunhaphang_h.tongsotienbangso.ToString()));
                        a = a + " đồng.";
                        
                        phieunhaphang_h.tongsotienbangchu = clsnumbertostring.DocSoThanhChu(long.Parse(phieunhaphang_h.tongsotienbangso.ToString()))+" đồng.";
                        

                        context.SubmitChanges();
                    }
                    
                    NX_phieunhaphang_h h = hs.ElementAt(0);


                    IEnumerable<NX_phieunhaphang_l> nxl = from c in context.NX_phieunhaphang_ls where c.NX_phieunhaphang_h.sophieu.Equals(sophieu) select c;

                    context.NX_phieunhaphang_ls.DeleteAllOnSubmit(nxl);
                    context.SubmitChanges();




                    double bitru = 0;
                    double thanhtoan = 0;
                    for (int i = 0; i < this.grdata.Rows.Count; i++)
                    {

                        
                        l = new NX_phieunhaphang_l();

                        //l.id_phieu = context.NX_phieunhaphang_ls.Count() + 1;
                        if (context.NX_phieunhaphang_ls.Count() > 0)
                        {
                            var id = (from c in context.NX_phieunhaphang_ls select c.id_phieu).Max() + 1;
                            l.id_phieu = id;
                        }
                        else
                        {
                            l.id_phieu = 1;

                        }

                        l.sophieu = sophieu;
                        if (this.grdata.Rows[i].Cells["mahh"].Value != null)
                        {
                            l.mahanghoa = this.grdata.Rows[i].Cells["mahh"].Value.ToString();
                        }
                        if (this.grdata.Rows[i].Cells["mahh"].Value != null)
                        {
                            l.trongluongdanhgia = double.Parse(this.grdata.Rows[i].Cells["danhgia"].Value.ToString());
                        }
                        if (h.loaimi == "2")
                        {
                            if (this.grdata.Rows[i].Cells["truluong"].Value != null)
                            {
                                l.sobao = double.Parse(this.grdata.Rows[i].Cells["truluong"].Value.ToString());
                                l.truluong = 0;
                            }


                        }
                        if (h.loaimi == "1")
                        {
                            if (this.grdata.Rows[i].Cells["truluong"].Value != null)
                            {
                                l.truluong = double.Parse(this.grdata.Rows[i].Cells["truluong"].Value.ToString());
                                l.sobao = 0;
                            }
                        }

                        if (this.grdata.Rows[i].Cells["thuyphan"].Value != null)
                        {
                            l.thuyphan = double.Parse(this.grdata.Rows[i].Cells["thuyphan"].Value.ToString());
                        }
                        if (this.grdata.Rows[i].Cells["tapchat"].Value != null)
                        {
                            l.tapchat = double.Parse(this.grdata.Rows[i].Cells["tapchat"].Value.ToString());
                        }
                        if (this.grdata.Rows[i].Cells["moc"].Value != null)
                        {
                            l.moc = double.Parse(this.grdata.Rows[i].Cells["moc"].Value.ToString());
                        }
                        if (this.grdata.Rows[i].Cells["dongia"].Value != null)
                        {
                            l.dongia = double.Parse(this.grdata.Rows[i].Cells["dongia"].Value.ToString());
                        }
                        //h.NX_phieunhaphang_ls.Add(l);
                        if (this.grdata.Rows[i].Cells["bitru"].Value != null)
                        {
                            l.bitru=double.Parse(this.grdata.Rows[i].Cells["bitru"].Value.ToString());
                            bitru +=(double)l.bitru;
                        }
                        if (this.grdata.Rows[i].Cells["thanhtoan"].Value != null)
                        {
                            l.trongluongthanhtoan = double.Parse(this.grdata.Rows[i].Cells["thanhtoan"].Value.ToString());
                        }
                        else
                        {
                            l.trongluongthanhtoan = 0;
                        }
                        context.NX_phieunhaphang_ls.InsertOnSubmit(l);

                        context.SubmitChanges();


                    }
                    double tongtrongluong;
                    double trongluongxe;
                    
                    foreach (NX_phieunhaphang_h phieunhaphang_h in hs)
                    {
                        if(phieunhaphang_h.tongtrongluong != null)
                        {
                            tongtrongluong=(double)phieunhaphang_h.tongtrongluong;
                        }else {
                            tongtrongluong=0;
                        }
                        if(phieunhaphang_h.trongluongxe != null)
                        {
                            trongluongxe = (double)phieunhaphang_h.trongluongxe;
                        }else 
                        {
                            trongluongxe = 0;
                        }
                        phieunhaphang_h.trongluongthanhtoan = tongtrongluong - trongluongxe - bitru;


                        context.SubmitChanges();
                    }
                   
                    MessageBox.Show("Lưu thành công", "Thông báo", MessageBoxButtons.OK);
                    //loaddata();
                    loaddanhsachphieunhaptheongay();

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Không lưu được.Lỗi: " + ex.Message, "Thông báo", MessageBoxButtons.OK);
            }

        }

        private void rdmituoi_Click(object sender, EventArgs e)
        {
            this.grdata.Columns["truluong"].HeaderText ="Trữ lượng bột";
            this.grdata.Columns["truluong"].ReadOnly = false;

        }

        private void dtptungay_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (dtptungay.Value > dtpdenngay.Value)
                {
                    this.dtpdenngay.Value = this.dtptungay.Value;

                }
                //DateTime tungay = this.dtptungay.Value;
                //DateTime denngay = this.dtpdenngay.Value;

                loaddanhsachphieunhaptheongay();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dtpdenngay_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (dtpdenngay.Value < dtptungay.Value)
                {
                    this.dtptungay.Value = this.dtpdenngay.Value;

                }
                //DateTime tungay = this.dtptungay.Value;
                //DateTime denngay = this.dtpdenngay.Value;

                loaddanhsachphieunhaptheongay();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

       
        private void txtmanvkiemdinh_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    string manv = this.txtmanvkiemdinh.Text;
                    
                    if (manv != "")
                    {
                        IEnumerable<DM_nhanvien> nhanviens = from c in context.DM_nhanviens where c.manv.Equals(manv) select c;
                        if (nhanviens.Count() > 0)
                        {
                            DM_nhanvien nhanvien = nhanviens.ElementAt(0);
                            this.txttennvkiemdinh.Text = nhanvien.hoten;

                        }
                        else
                        {
                            
                            //Tim kiem nhan vien
                            MODULE_TIENICH.cls_tienich cls = new MODULE_TIENICH.cls_tienich();
                            cls.ShowForm("frm_timkiemnhanvien");
                            this.txtmanvkiemdinh.Text = cls._manv;
                            nhanviens = from c in context.DM_nhanviens where c.manv.Equals(cls._manv) select c;
                            DM_nhanvien nhanvien = nhanviens.ElementAt(0);
                            this.txttennvkiemdinh.Text = nhanvien.hoten;
                        }
                    }
                    else
                    {
                        //Tim kiem nhan vien
                        MODULE_TIENICH.cls_tienich cls = new MODULE_TIENICH.cls_tienich();
                        cls.ShowForm("frm_timkiemnhanvien");
                        this.txtmanvkiemdinh.Text = cls._manv;
                        IEnumerable<DM_nhanvien> nhanviens = from c in context.DM_nhanviens where c.manv.Equals(cls._manv) select c;
                        DM_nhanvien nhanvien = nhanviens.ElementAt(0);
                        this.txttennvkiemdinh.Text = nhanvien.hoten;
                    }
                }
            }
            catch (Exception ex)
            {
 
            }
        }

        private void txtmanvnhaplieu_KeyDown(object sender, KeyEventArgs e)
        {

            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    string manv = this.txtmanvnhaplieu.Text;

                    if (manv != "")
                    {
                        IEnumerable<DM_nhanvien> nhanviens = from c in context.DM_nhanviens where c.manv.Equals(manv) select c;
                        if (nhanviens.Count() > 0)
                        {
                            DM_nhanvien nhanvien = nhanviens.ElementAt(0);
                            this.txttennvnhaplieu.Text = nhanvien.hoten;

                        }
                        else
                        {

                            //Tim kiem nhan vien
                            MODULE_TIENICH.cls_tienich cls = new MODULE_TIENICH.cls_tienich();
                            cls.ShowForm("frm_timkiemnhanvien");
                            this.txtmanvnhaplieu.Text = cls._manv;
                            nhanviens = from c in context.DM_nhanviens where c.manv.Equals(cls._manv) select c;
                            DM_nhanvien nhanvien = nhanviens.ElementAt(0);
                            this.txttennvnhaplieu.Text = nhanvien.hoten;
                        }
                    }
                    else
                    {
                        //Tim kiem nhan vien
                        MODULE_TIENICH.cls_tienich cls = new MODULE_TIENICH.cls_tienich();
                        cls.ShowForm("frm_timkiemnhanvien");
                        this.txtmanvnhaplieu.Text = cls._manv;
                        IEnumerable<DM_nhanvien> nhanviens = from c in context.DM_nhanviens where c.manv.Equals(cls._manv) select c;
                        DM_nhanvien nhanvien = nhanviens.ElementAt(0);
                        this.txttennvnhaplieu.Text = nhanvien.hoten;
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void getrowdata()
        
        {
            if (currenrowindex < grdanhsach.Rows.Count )
            {
                string sophieu = grdanhsach.Rows[currenrowindex].Cells["sophieu"].Value.ToString();
                this.txtsophieu.Text = sophieu;
                getinfobill();
                
            }

        }
       

        private void grdata_Click(object sender, EventArgs e)
        {
            
        }

        private void btnext_Click(object sender, EventArgs e)
        {
            try
            {
                if (grdanhsach.Rows.Count > 0)
                {
                    this.grdanhsach.Rows[currenrowindex].Selected = false;
                    if (currenrowindex < this.grdanhsach.Rows.Count - 1)
                    {
                        currenrowindex = currenrowindex + 1;
                    }

                    this.grdanhsach.Rows[currenrowindex].Selected = true;

                    getrowdata();
                }
            }catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btlast_Click(object sender, EventArgs e)
        {
             try
            {
                if (grdanhsach.Rows.Count > 0)
                {
                this.grdanhsach.Rows[currenrowindex].Selected = false;

                currenrowindex = this.grdanhsach.Rows.Count - 1;


                this.grdanhsach.Rows[currenrowindex].Selected = true;

                getrowdata();
                }
            }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.Message);
             }
        }

        private void btprev_Click(object sender, EventArgs e)
        {
            try
            {
                if (grdanhsach.Rows.Count > 0)
                {
                    this.grdanhsach.Rows[currenrowindex].Selected = false;
                    if (currenrowindex > 0)
                    {
                        currenrowindex = currenrowindex - 1;
                    }

                    this.grdanhsach.Rows[currenrowindex].Selected = true;

                    getrowdata();
                }
            }
            catch (Exception ex)
            {  Console.WriteLine(ex.Message);
             
            }

        }

        private void btfist_Click(object sender, EventArgs e)
        {
            try
            {
                if (grdanhsach.Rows.Count > 0)
                {
                    this.grdanhsach.Rows[currenrowindex].Selected = false;

                    currenrowindex = 0;


                    this.grdanhsach.Rows[currenrowindex].Selected = true;

                    getrowdata();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        private void txtmachuhang_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                
                if (e.KeyCode == Keys.Enter)
                {
                    string machuhang = this.txtmachuhang.Text;
                    if (machuhang != "")
                    {
                        IEnumerable<DM_chuhang> chuhangs = from c in context.DM_chuhangs where c.machuhang.Equals(machuhang) select c;
                        if (chuhangs.Count() > 0)
                        {
                            DM_chuhang chuhang = chuhangs.ElementAt(0);
                            this.txttenchuhang.Text = chuhang.tenchuhang;
                            this.txtdiachi.Text = chuhang.diachi;

                        }
                        else
                        {
                            MODULE_TIENICH.cls_tienich cls = new MODULE_TIENICH.cls_tienich();
                            cls.ShowForm("frm_timkiemchuhang");
                            this.txtmachuhang.Text = cls._makhachhang;
                            chuhangs = from c in context.DM_chuhangs where c.machuhang.Equals(this.txtmachuhang.Text) select c;
                            if (chuhangs.Count() > 0)
                            {
                                DM_chuhang chuhang = chuhangs.ElementAt(0);
                                this.txttenchuhang.Text = chuhang.tenchuhang;
                                this.txtdiachi.Text = chuhang.diachi;
                            }
                        }
                    }
                    else
                    {

                        MODULE_TIENICH.cls_tienich cls = new MODULE_TIENICH.cls_tienich();
                        cls.ShowForm("frm_timkiemchuhang");
                        this.txtmachuhang.Text = cls._makhachhang;
                        IEnumerable<DM_chuhang> chuhangs = from c in context.DM_chuhangs where c.machuhang.Equals(this.txtmachuhang.Text) select c;
                        if (chuhangs.Count() > 0)
                        {
                            DM_chuhang chuhang = chuhangs.ElementAt(0);
                            this.txttenchuhang.Text = chuhang.tenchuhang;
                            this.txtdiachi.Text = chuhang.diachi;
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void grdanhsach_Click(object sender, EventArgs e)
        {
            try
            {
                
                    currenrowindex = this.grdanhsach.CurrentRow.Index;
                    this.grdanhsach.Rows[currenrowindex].Selected = true;
                    getrowdata();
                    if (status_bill == 1)
                    {
                        btDelete.Enabled = true;
                    }

            }
            catch (Exception ex)
            { 
            }
        }

        private void txtkeyword_TextChanged(object sender, EventArgs e)
        {
            this.tabControl1.SelectedIndex = 1;
            // this.tabControl1.TabPages[1].Select();
            string keyword = txtkeyword.Text;
            string tungay, denngay;
            string d, m, y;

            if (this.dtptungay.Value.Day >= 10)
            {
                d = this.dtptungay.Value.Day.ToString();
            }
            else
            {
                d = "0" + this.dtptungay.Value.Day.ToString();
            }

            if (this.dtptungay.Value.Month >= 10)
            {
                m = this.dtptungay.Value.Month.ToString();
            }
            else
            {
                m = "0" + this.dtptungay.Value.Month.ToString();
            }
            y = this.dtptungay.Value.Year.ToString();
            tungay = d + "/" + m + "/" + y;
            if (this.dtpdenngay.Value.Day >= 10)
            {
                d = this.dtpdenngay.Value.Day.ToString();
            }
            else
            {
                d = "0" + this.dtpdenngay.Value.Day.ToString();
            }

            if (this.dtpdenngay.Value.Month >= 10)
            {
                m = this.dtpdenngay.Value.Month.ToString();
            }
            else
            {
                m = "0" + this.dtpdenngay.Value.Month.ToString();
            }
            y = this.dtpdenngay.Value.Year.ToString();
            denngay = d + "/" + m + "/" + y;

            //this.grdata.Columns["truluong"].HeaderText = "Trữ lượng bột";
            List<KCS_getdanhsachphieunhaptheongayResult> danhsachphieunhaps = (from c in context.KCS_getdanhsachphieunhaptheongay(tungay, denngay) where c.machuhang.StartsWith(keyword) select c).ToList();

            grdanhsach.Rows.Clear();
            for (int i = 0; i < danhsachphieunhaps.Count(); i++)
            {
                KCS_getdanhsachphieunhaptheongayResult phieunhap = danhsachphieunhaps.ElementAt(i);
                grdanhsach.Rows.Add();
                grdanhsach.Rows[i].Cells["sophieu"].Value = phieunhap.sophieu;
                grdanhsach.Rows[i].Cells["ngay"].Value = phieunhap.giovao;
                grdanhsach.Rows[i].Cells["machuhang"].Value = phieunhap.machuhang;
                grdanhsach.Rows[i].Cells["tenchuhang"].Value = phieunhap.tenchuhang;
                grdanhsach.Rows[i].Cells["diachi"].Value = phieunhap.diachi;
                grdanhsach.Rows[i].Cells["soxe"].Value = phieunhap.soxe;
                grdanhsach.Rows[i].Cells["trongluongthuan"].Value = phieunhap.trongluongthanhtoan;
                grdanhsach.Rows[i].Cells["sotien"].Value = phieunhap.tongsotienbangso;

                grdanhsach.Rows[i].DefaultCellStyle.ForeColor = Color.Red;//Mau phieu moi nhap
                IEnumerable<NX_phieunhaphang_l> kiemdinhs = from c in context.NX_phieunhaphang_ls where c.sophieu.Equals(phieunhap.sophieu) select c;
                if (kiemdinhs.Count() > 0)
                {
                    //grdata.Rows[i].Cells["chk"].ReadOnly = true;

                    grdanhsach.Rows[i].DefaultCellStyle.ForeColor = Color.MediumBlue;//System.Drawing.Color.Red;
                }
                IEnumerable<KT_hoadon_l> hoadons = from c in context.KT_hoadon_ls where c.sophieunhap.Equals(phieunhap.sophieu) select c;
                if (hoadons.Count() > 0)
                {
                    //grdata.Rows[i].Cells["chk"].ReadOnly = true;
                    grdanhsach.Rows[i].DefaultCellStyle.ForeColor = Color.Black;//System.Drawing.Color.Red;

                    //flag = false;
                }
            }




            //IEnumerable<NX_phieunhaphang_h> phieukiemdinhs = from c in context.NX_phieunhaphang_hs where c.DM_chuhang.tenchuhang.Contains(keyword) select c;//where c.NX_phieunhaphang_ls.Count() > 0 select c;
            //grdanhsach.Rows.Clear();
            //for (int i = 0; i < phieukiemdinhs.Count(); i++)
            //{
            //    NX_phieunhaphang_h phieunhap = phieukiemdinhs.ElementAt(i);
            //    grdanhsach.Rows.Add();
            //    grdanhsach.Rows[i].Cells["sophieu"].Value = phieunhap.sophieu;
            //    grdanhsach.Rows[i].Cells["ngay"].Value = phieunhap.giovao;
            //    grdanhsach.Rows[i].Cells["machuhang"].Value = phieunhap.machuhang;
            //    grdanhsach.Rows[i].Cells["tenchuhang"].Value = phieunhap.DM_chuhang.tenchuhang;
            //    grdanhsach.Rows[i].Cells["diachi"].Value = phieunhap.DM_chuhang.diachi;
            //    grdanhsach.Rows[i].Cells["soxe"].Value = phieunhap.soxe;
            //    grdanhsach.Rows[i].Cells["trongluongthuan"].Value = phieunhap.trongluongthanhtoan;
            //    grdanhsach.Rows[i].Cells["sotien"].Value = phieunhap.tongsotienbangso;


            //    grdanhsach.Rows[i].DefaultCellStyle.ForeColor = Color.Red;//Mau phieu moi nhap
            //    IEnumerable<NX_phieunhaphang_l> kiemdinhs = from c in context.NX_phieunhaphang_ls where c.sophieu.Equals(phieunhap.sophieu) select c;
            //    if (kiemdinhs.Count() > 0)
            //    {
            //        //grdata.Rows[i].Cells["chk"].ReadOnly = true;

            //        grdanhsach.Rows[i].DefaultCellStyle.ForeColor = Color.MediumBlue;//System.Drawing.Color.Red;
            //    }
            //    IEnumerable<KT_hoadon_l> hoadons = from c in context.KT_hoadon_ls where c.sophieunhap.Equals(phieunhap.sophieu) select c;
            //    if (hoadons.Count() > 0)
            //    {
            //        //grdata.Rows[i].Cells["chk"].ReadOnly = true;
            //        grdanhsach.Rows[i].DefaultCellStyle.ForeColor = Color.Black;//System.Drawing.Color.Red;

            //        //flag = false;
            //    }
            //}
            
        }

        private void txtkeyword_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    string sophieu = this.txtkeyword.Text;
                    List<KCS_timkiemphieunhapResult> phieunhaps = context.KCS_timkiemphieunhap(sophieu).ToList();

                    if (phieunhaps.Count > 0)
                    {

                        grdanhsach.Rows.Clear();
                        for (int i = 0; i < phieunhaps.Count; i++)
                        {
                            grdanhsach.Rows.Add();
                            KCS_timkiemphieunhapResult phieunhap = phieunhaps.ElementAt(i);
                            grdanhsach.Rows[i].Cells["sophieu"].Value = phieunhap.sophieu;
                            grdanhsach.Rows[i].Cells["ngay"].Value = phieunhap.giovao;
                            grdanhsach.Rows[i].Cells["machuhang"].Value = phieunhap.machuhang;
                            grdanhsach.Rows[i].Cells["tenchuhang"].Value = phieunhap.tenchuhang;
                            grdanhsach.Rows[i].Cells["diachi"].Value = phieunhap.diachi;
                            grdanhsach.Rows[i].Cells["soxe"].Value = phieunhap.soxe;
                            grdanhsach.Rows[i].Cells["trongluongthuan"].Value = phieunhap.trongluongthanhtoan;
                            grdanhsach.Rows[i].Cells["sotien"].Value = phieunhap.tongsotienbangso;


                        }
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void tabPage1_Click(object sender, EventArgs e)
        {

        }

        private void txtsophieu_Click(object sender, EventArgs e)
        {

        }

        private void btAdd_Click_1(object sender, EventArgs e)
        {
            this.grdata.Rows.Add();
        }

        private void btDelete_Click(object sender, EventArgs e)
        {

            if (MessageBox.Show("Bạn chắc chắn muốn xóa phiếu này không?", "Xác nhận", MessageBoxButtons.YesNo) == DialogResult.Yes) 
            {

                try
                {
                    IEnumerable<NX_phieunhaphang_l> nhaphanglines = from c in context.NX_phieunhaphang_ls where c.NX_phieunhaphang_h.sophieu.Equals(txtsophieu.Text) select c;
                    foreach (NX_phieunhaphang_l l in nhaphanglines)
                    {
                        context.NX_phieunhaphang_ls.DeleteOnSubmit(l);
                        context.SubmitChanges();
                    }
                    MessageBox.Show("Xoá thành công.");
                    loaddanhsachphieunhaptheongay();
                    //loaddata();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Không xoá được.Lỗi: " + ex.Message);
                }
            }


            //this.grdata.Rows.Clear();
            //double tongtien = 0;
            //this.txttongtien.Text = tongtien.ToString();
            //IEnumerable<KT_hoadon_l> hoadons = from c in context.KT_hoadon_ls where c.sophieunhap.Equals(txtsophieu.Text) select c;
            //if (hoadons.Count() == 0)
            //{

            //}
            //else
            //{

            //}
        }

        private void grdata_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            //Tinh tong tien
            double tongtien = 0;


            for (int i = 0; i < this.grdata.Rows.Count; i++)
            {
                if (grdata.Rows[i].Cells["thanhtien"].Value != null)
                {
                    tongtien += double.Parse(grdata.Rows[i].Cells["thanhtien"].Value.ToString());
                }
            }
            this.txttongtien.Text = tongtien.ToString();
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}


        }

        private void grdanhsach_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Down)
                {
                    //this.grdanhsach.Rows[currenrowindex].Selected = false;

                    if (currenrowindex < this.grdanhsach.Rows.Count - 1)
                    {
                       
                        currenrowindex = currenrowindex + 1;
                   
                    }
                    this.grdanhsach.Rows[currenrowindex].Selected = true;
                   

                    getrowdata();


                }
                if (e.KeyCode == Keys.Up)
                {
                    //this.grdanhsach.Rows[currenrowindex].Selected = false;
                    if (currenrowindex > 0)
                    {
                        
                        currenrowindex = currenrowindex - 1;
                       
                    }

                    this.grdanhsach.Rows[currenrowindex].Selected = true;

                    getrowdata();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void btPrint_Click(object sender, EventArgs e)
        {
            try
            {


                string sophieu = this.txtsophieu.Text;
                frm_inphieubiennhan frm = new frm_inphieubiennhan();
                frm._sophieu = sophieu;
                frm.Show();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }

        }

        private void grdata_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {




            }
        }

        private void grdata_CurrentCellChanged(object sender, EventArgs e)
        {
          
        }

        private void grdata_CellLeave(object sender, DataGridViewCellEventArgs e)
        {

            if (this.tabControl1.SelectedIndex == 0)
            {
                if (e.ColumnIndex == 0)
                {

                    string mahh;
                    if (this.grdata.CurrentCell.Value != null)
                    {
                        mahh = this.grdata.CurrentCell.Value.ToString();


                        IEnumerable<DM_hanghoa> hanghoas = from c in context.DM_hanghoas where c.mahang.Equals(mahh) select c;

                        if (hanghoas.Count() > 0)
                        {
                            DM_hanghoa h = hanghoas.ElementAt(0);
                            this.grdata.CurrentRow.Cells["tenhh"].Value = h.tenhang;
                            IEnumerable<dongiahanghoamoinhat> dongias = from c in context.dongiahanghoamoinhats where c.mahang.Equals(h.mahang) select c;
                            if (dongias.Count() > 0)
                            {
                                dongiahanghoamoinhat dg = dongias.ElementAt(0);
                                this.grdata.CurrentRow.Cells["dongia"].Value = dg.dongia;
                                this.grdata.CurrentRow.Cells["dongiahienhanh"].Value = dg.dongia;
                                double soluong = double.Parse(this.grdata.CurrentRow.Cells["thanhtoan"].Value.ToString());
                                double thanhtien = (double)dg.dongia * soluong;
                                this.grdata.CurrentRow.Cells["thanhtien"].Value = thanhtien;
                            }


                        }
                        else
                        {
                            MODULE_TIENICH.cls_tienich cls = new MODULE_TIENICH.cls_tienich();
                            cls.ShowForm("frm_timkiemhanghoa");
                            this.grdata.CurrentCell.Value = cls._mahanghoa;
                            mahh = this.grdata.CurrentCell.Value.ToString();
                            hanghoas = from c in context.DM_hanghoas where c.mahang.Equals(mahh) select c;
                            DM_hanghoa h = hanghoas.ElementAt(0);
                            this.grdata.CurrentRow.Cells["tenhh"].Value = h.tenhang;
                            IEnumerable<dongiahanghoamoinhat> dongias = from c in context.dongiahanghoamoinhats where c.mahang.Equals(h.mahang) select c;
                            if (dongias.Count() > 0)
                            {
                                dongiahanghoamoinhat dg = dongias.ElementAt(0);
                                this.grdata.CurrentRow.Cells["dongia"].Value = dg.dongia;
                                this.grdata.CurrentRow.Cells["dongiahienhanh"].Value = dg.dongia;
                                double soluong = double.Parse(this.grdata.CurrentRow.Cells["thanhtoan"].Value.ToString());
                                double thanhtien = (double)dg.dongia * soluong;
                                this.grdata.CurrentRow.Cells["thanhtien"].Value = thanhtien;
                            }


                        }
                    }
                    else
                    {

                        MODULE_TIENICH.cls_tienich cls = new MODULE_TIENICH.cls_tienich();
                        cls.ShowForm("frm_timkiemhanghoa");
                        this.grdata.CurrentCell.Value = cls._mahanghoa;
                        mahh = this.grdata.CurrentCell.Value.ToString();
                        IEnumerable<DM_hanghoa> hanghoas = from c in context.DM_hanghoas where c.mahang.Equals(mahh) select c;
                        DM_hanghoa h = hanghoas.ElementAt(0);
                        this.grdata.CurrentRow.Cells["tenhh"].Value = h.tenhang;
                        IEnumerable<dongiahanghoamoinhat> dongias = from c in context.dongiahanghoamoinhats where c.mahang.Equals(h.mahang) select c;
                        if (dongias.Count() > 0)
                        {
                            dongiahanghoamoinhat dg = dongias.ElementAt(0);
                            this.grdata.CurrentRow.Cells["dongia"].Value = dg.dongia;
                            this.grdata.CurrentRow.Cells["dongiahienhanh"].Value = dg.dongia;
                            double soluong = double.Parse(this.grdata.CurrentRow.Cells["thanhtoan"].Value.ToString());
                            //
                            double thanhtien = (double)dg.dongia * soluong;
                            this.grdata.CurrentRow.Cells["thanhtien"].Value = thanhtien;
                        }


                    }
                    //////////Tinh lai tong tien
                    double tongtien = 0;
                    for (int i = 0; i < this.grdata.Rows.Count; i++)
                    {
                        if (grdata.Rows[i].Cells["thanhtien"].Value != null && grdata.Rows[i].Cells["thanhtien"].Value.ToString() != "")
                        {
                            tongtien += double.Parse(grdata.Rows[i].Cells["thanhtien"].Value.ToString());
                        }
                    }
                    this.txttongtien.Text = tongtien.ToString();

                }
            }

        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //MessageBox.Show(this.tabControl1.SelectedIndex.ToString());
        }

        private void btExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            try
            {


                string sophieu = this.txtsophieu.Text;
                frm_inphieubiennhan frm = new frm_inphieubiennhan();
                frm._sophieu = sophieu;
                frm.Show();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
        }

        

       
    }
}
